package com.hutao.manage.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.hutao.manage.pojo.User;
import com.hutao.manage.util.CookieUtils;
import com.hutao.manage.util.HttpClientUtil;
import com.hutao.manage.util.MD5;

/**
 * 用户登录控制器
 * 
 * @author h2oco2
 *
 */
@RequestMapping("/user")
@Controller
public class LoginController {
	
	@Value("${login.url.new}")
	private String loginUrlNew;
	
	
	@GetMapping("/toLogin")
	public String toLogin() {
		return "/login";
	}

	@RequestMapping("/error")
	public String error() {
		return "/error";
	}

	/**
	 * 新系统
	 * 用户的登录
	 * 
	 * @param loginName
	 * @param password
	 * @param request
	 * @param response
	 * @return
	 */
	@PostMapping("/userLogin")
	public String login(String loginName, String password, HttpServletRequest request,
			HttpServletResponse response) {

		try {
			// 远程调用sso系统
			// String userJson = HttpClientUtil.doPost(loginUrl, params);
			String contextPath = request.getContextPath();
			int index = contextPath.lastIndexOf("/");
			contextPath = contextPath.substring(index+1);

			Map<String, String> params = new HashMap<>();
			params.put("username", loginName);
			params.put("password", MD5.md5(password));
			params.put("contextPath", contextPath);
			
			// 远程调用sso登录系统
			String userJson = HttpClientUtil.doPost(loginUrlNew, params);
			JSONObject userMap = JSONObject.parseObject(userJson);
			
			if ((boolean) userMap.get("isSuccess")) {
				Subject subject = SecurityUtils.getSubject();
				UsernamePasswordToken token = new UsernamePasswordToken(loginName, MD5.md5(password));
				Session session = subject.getSession();
				session.setAttribute("contextPath", contextPath);
				session.setAttribute("password", password);
				subject.login(token);
				
				User user = new User();
				user.setId((String)userMap.get("id"));
				user.setLoginName(loginName);
				user.setPassword(password);
				user.setContextPath(contextPath);
				user.setMedicalMainstayId((String)userMap.get("medicalMainstayId"));
				user.setName(userMap.get("name")!=null&&userMap.get("name")!=""?(String)userMap.get("name"):"");
				session.setAttribute("user", user);
				session.setAttribute("loginName", userMap.get("name"));
				session.setTimeout(1800000L);
				String officeCode = userMap.get("officeCode")!=null&&userMap.get("officeCode")!=""?(String)userMap.get("officeCode"):"";
				String officeName = userMap.get("officeName")!=null&&userMap.get("officeName")!=""?(String)userMap.get("officeName"):"";
				
				
				//设置cookie的值 30分钟后过期
				CookieUtils.setCookie(request, response, "TT_TOKEN", loginName, 15000);
				CookieUtils.setCookie(request, response, "userName", user.getName(), 15000);
				CookieUtils.setCookie(request, response, "officeCode", officeCode, 15000);
				CookieUtils.setCookie(request, response, "officeName", officeName, 15000);
				CookieUtils.setCookie(request, response, "medicalMainstayId", (String)userMap.get("medicalMainstayId"), 15000);
				CookieUtils.setCookie(request, response, "userId", (String)userMap.get("id"), 15000);
				/*return "index.index";*/
				return "redirect:/page/index";
			}
			request.setAttribute("loginName", loginName);
			request.setAttribute("password", password);
			request.setAttribute("errorMsg", userMap.get("message"));
			
			return "/login";
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("loginName", loginName);
			request.setAttribute("password", password);
			request.setAttribute("errorMsg", e.getMessage());
			return "/login";
		}
		
	}

	@RequestMapping("/logout")
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		//获取shiro的subiect获取session
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		String orgCode = (String) session.getAttribute("orgCode");
		//获取cookie
		Cookie[] cookies = request.getCookies();
		//清空cookie
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				String cookieName = cookie.getName();
				String cookieValue = cookie.getValue();
				if (cookieName.contains("TT_TOKEN") && null != cookieValue) {
					CookieUtils.deleteCookie(request, response, cookieName);
					CookieUtils.deleteCookie(request, response, "userName");
				}

			}
		}
		//shiro退出
		if (subject.isAuthenticated()) {
			subject.logout();
		}
		return "/login";
	}
	
	
	
	@RequestMapping("/unAnthority")
	public String unAnthority(HttpServletRequest request) {
		return "/error/unAnthority";
	}

	
	
	/**
	 * 没有登录的用户跳转到此方法
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/index")
	public String index(HttpServletRequest request) {
		return "/index";
	}

	
	
}
